<?php

namespace App\Service\Feishu\Base;

use App\Models\Common\ConfigModel;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;

class BaseService
{
    protected string $domain;

    private string $appid;

    private string $appSecret;

    // 小程序
    public function __construct(string $appid)
    {
        $this->domain    = 'https://open.feishu.cn/';
        $this->appid     = $appid;
        $this->appSecret = ConfigModel::getFsConfigByAppId($appid)['appSecret'] ?? '';
    }

    private function getTenantAccessToken()
    {
        $key = 'feishu_base_access_token:' . $this->appid;

        if (!($token = Cache::get($key))) {
            $client  = new Client();
            $headers = ['Content-Type' => 'application/json'];
            $body    = json_encode(['app_id' => $this->appid, 'app_secret' => $this->appSecret]);
            $request = new Request('POST', $this->domain . 'open-apis/auth/v3/tenant_access_token/internal',
                $headers, $body);
            $res     = $client->sendAsync($request)->wait();
            $res     = json_decode($res->getBody()->getContents(), 1);
            Cache::put($key, $res['tenant_access_token'], $res['expire'] - 60);
            $token = $res['tenant_access_token'];
        }
        return 'Bearer ' . $token;
    }

    protected function curlGet(string $url)
    {
        $client  = new Client();
        $headers = [
            'Authorization' => $this->getTenantAccessToken()
        ];

        $request = new Request('GET', $this->domain . $url,
            $headers);
        $res     = $client->sendAsync($request)->wait();
        return json_decode($res->getBody()->getContents(), 1);
    }

    protected function formatData(array $data)
    {
        if ($data['msg'] == 'ok') {
            return $data['data'];
        }

        return $data;
    }

    // 飞书数据解密
    protected function decryption()
    {
        //
    }
}
